package com.simblog.common.utils;

import java.util.Base64;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.simblog.common.SessionEntity;
import com.simblog.oaknt.domain.User;

public class TokenUtil {
	private static final Logger logger = LoggerFactory.getLogger(TokenUtil.class);
	
	private static RedisUtil redisUtil;
	
	public  RedisUtil getRedisUtil() {
		return redisUtil;
	}

	public  void setRedisUtil(RedisUtil redisUtil) {
		TokenUtil.redisUtil = redisUtil;
	}
	
	//token的有效期
	private static long tokenValidityPeriod = Long.parseLong(PropertiesUtil.getString(PropertiesUtil.load("global.properties"), "token.validity.period"));
	
	
	/**
	 * 生成token
	 * 该代码只能在jdk1.8中使用
	 * @return 返回生成的token
	 */
	public static String generateToken(){
		String uuid = UUID.randomUUID().toString();
		String token = uuid.replaceAll("-", "") + "_" + String.valueOf(System.currentTimeMillis());
		return Base64.getEncoder().encodeToString(token.getBytes());
	}
	
	/**
	 * 判断token是否失效
	 */
	public static boolean isExpired(String token){
		//把token进行base64解码
		String decodeToken = new String(Base64.getDecoder().decode(token));
		//获取token的时间
		if(decodeToken.contains("_")){
			long tokenTime = Long.parseLong(decodeToken.split("_")[1]);
			long diff = (System.currentTimeMillis() - tokenTime)/1000;
			if( diff > tokenValidityPeriod * 3600){
				logger.error("token已经过{}s",diff);
				return false;
			}else{
				return true;
			}
		}else{
			logger.error("token中未包含时间戳，请检查token");
			return false;
		}
	}
	
	
	/**
	 * 根据token获取存在redis的SessionEntity数据
	 */
	public static SessionEntity getSessionEntity(String token){
		JSONObject jsonObject = redisUtil.get(token);
		try{
			SessionEntity sessionEntity = JSON.toJavaObject(jsonObject, SessionEntity.class);
			return sessionEntity;
		}catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * 保存SessionEntity到redis
	 */
	public static void setSessionEntity(String key,SessionEntity sessionEntity){
		redisUtil.set(key, sessionEntity);
	}
	
	public static void deleteSessionEntity(String key){
		redisUtil.delete(key);
	}
	
	/**
	 * 根据token获取redis中User数据
	 * @param token
	 * @return
	 */
	public static User getUser(String token){
		SessionEntity sessionEntity = getSessionEntity(token);
		if(sessionEntity == null){
			return null;
		}
		return sessionEntity.getUser();
	}
	
	
	
	
}
